package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {

    // "0"  +  timestamp(31) + increment(31)

//    System.out.println(LocalDateTime.of(2025,6,1,0,0,0).toEpochSecond(ZoneOffset.UTC));
    private static final long INIT_TIMESTAMP = 1749141984L;

    private static final long COUNT_BITS = 32L;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public long nextId(String keyPrefix) {
        long nowTime = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        long timeStamp = nowTime-INIT_TIMESTAMP;
        Long increment = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + " " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy:MM:dd")));
        return timeStamp<<COUNT_BITS | increment;

    }


}
